<template>
  <div class="app-container">
    <div class="top-section-container">
      <div class="content-header">
        <h1>预约管理/<small>预约设置</small></h1>
        <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>预约管理</el-breadcrumb-item>
          <el-breadcrumb-item>预约设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="bottom-section-container">
      <div class="calendar-section">
        <div class="calendar-header">
          <el-button @click="pickPreMonth">上月</el-button>
          <el-button @click="goCurrentMonth" class="gotoday-button">本月</el-button>
          <el-button @click="pickNextMonth">下月</el-button>
          <span class="current-month-display year-month">{{ currentYear }} 年 {{ currentMonth }} 月</span>
        </div>
        <div class="calendar-wrapper">
          <div class="week-header">
            <span>周一</span><span>周二</span><span>周三</span><span>周四</span><span>周五</span><span>周六</span><span>周日</span>
          </div>
          <div class="days-grid">
            <div
                v-for="(day, index) in calendarDays"
                :key="index"
                :class="[
                'day-item',
                { 'is-current-month': day.isCurrentMonth },
                { 'is-fully-booked': day.orderSetting && day.orderSetting.numberReservations > 0 && day.orderSetting.numberReservations === day.orderSetting.reservationsAvailable },
                { 'has-order-setting': day.orderSetting && !(day.orderSetting.numberReservations > 0 && day.orderSetting.numberReservations === day.orderSetting.reservationsAvailable) }
              ]"
                @click="handleDayClick(day)"
            >
              <span class="day-number">{{ day.dayOfMonth }}</span>
              <div v-if="day.orderSetting" class="order-info">
                <p class="available-text">可预约: <span class="available">{{ day.orderSetting.numberReservations }}</span></p>
                <p class="reserved-text">已预约: <span class="reserved">{{ day.orderSetting.reservationsAvailable }}</span></p>
              </div>
              <div v-else class="no-order-info calendar-p">
                <p>未设置</p>
              </div>
            </div>
          </div>
        </div>
      </div>


      <el-dialog
          v-model="dialogVisible"
          :title="dialogTitle"
          width="400px"
          @close="handleDialogClose"
      >
        <el-form :model="orderSettingForm" ref="orderSettingFormRef" label-width="120px">
          <el-form-item label="预约日期">
            <span>{{ orderSettingForm.orderDate }}</span>
          </el-form-item>
          <el-form-item label="最大预约人数" prop="numberReservations">
            <el-input-number
                v-model="orderSettingForm.numberReservations"
                :min="0"
                controls-position="right"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="已预约人数">
            <span>{{ orderSettingForm.reservationsAvailable }}</span>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitOrderSetting">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
// 假设这里引入了用于后端请求的 axios
// import axios from 'axios';

// 当前年份和月份
const currentYear = ref(new Date().getFullYear());
const currentMonth = ref(new Date().getMonth() + 1); // 月份从1开始

// 存储当前月份的预约设置数据 { 'YYYY-MM-DD': { date: '...', numberReservations: 0, reservationsAvailable: 0 } }
const monthlyOrderSettings = reactive({});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('预约设置');
const orderSettingForm = reactive({
  orderDate: '',
  numberReservations: 0,
  reservationsAvailable: 0, // 已预约人数，通常从后端获取，不可手动修改
});
const orderSettingFormRef = ref(null); // 表单引用

// 计算当前月份的日历天数数组
const calendarDays = computed(() => {
  const days = [];
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1);
  const lastDay = new Date(currentYear.value, currentMonth.value, 0);
  // 获取本月第一天是星期几 (0: 周日, 1: 周一, ..., 6: 周六)
  // 如果是周日 (0), 转换为 7, 方便后续计算
  const startDayOfWeek = firstDay.getDay() === 0 ? 7 : firstDay.getDay();

  // 填充上个月的末尾几天（占位符），使其从周一开始对齐
  for (let i = 1; i < startDayOfWeek; i++) {
    days.push({ dayOfMonth: '', isCurrentMonth: false });
  }

  // 填充当前月的日期
  for (let i = 1; i <= lastDay.getDate(); i++) {
    const dateStr = `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
    days.push({
      dayOfMonth: i,
      isCurrentMonth: true,
      fullDate: dateStr,
      orderSetting: monthlyOrderSettings[dateStr] || null,
    });
  }
  return days;
});

// 获取指定月份的预约设置数据
const fetchOrderSetting = async () => {
  console.log(`Fetching order settings for ${currentYear.value}-${currentMonth.value}`);
  // 实际项目中，这里会发送 Axios 请求到后端 API
  // 示例API: GET /ordersetting/getMonthData?year=YYYY&month=MM
  // 模拟数据结构: [{ date: 'YYYY-MM-DD', numberReservations: 100, reservationsAvailable: 10 }]
  const mockMonthlyData = [
    { date: `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-05`, numberReservations: 100, reservationsAvailable: 25 },
    { date: `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-10`, numberReservations: 80, reservationsAvailable: 50 },
    { date: `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-15`, numberReservations: 120, reservationsAvailable: 120 }, // 已满
    { date: `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-20`, numberReservations: 90, reservationsAvailable: 10 },
    { date: `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-25`, numberReservations: 50, reservationsAvailable: 50 }, // 另一个已满
  ];

  // 清空旧数据
  for (const key in monthlyOrderSettings) {
    delete monthlyOrderSettings[key];
  }
  // 填充新数据
  mockMonthlyData.forEach(item => {
    monthlyOrderSettings[item.date] = item;
  });
};

// 切换到上个月
const pickPreMonth = () => {
  if (currentMonth.value === 1) {
    currentMonth.value = 12;
    currentYear.value--;
  } else {
    currentMonth.value--;
  }
  fetchOrderSetting();
};

// 切换到下个月
const pickNextMonth = () => {
  if (currentMonth.value === 12) {
    currentMonth.value = 1;
    currentYear.value++;
  } else {
    currentMonth.value++;
  }
  fetchOrderSetting();
};

// 切换到本月
const goCurrentMonth = () => {
  const today = new Date();
  currentYear.value = today.getFullYear();
  currentMonth.value = today.getMonth() + 1;
  fetchOrderSetting();
};

// 点击某一天
const handleDayClick = (day) => {
  if (!day.isCurrentMonth || !day.fullDate) {
    return; // 不处理非本月的日期或空占位符
  }
  dialogTitle.value = '预约设置 - ' + day.fullDate;
  Object.assign(orderSettingForm, {
    orderDate: day.fullDate,
    numberReservations: day.orderSetting ? day.orderSetting.numberReservations : 0,
    reservationsAvailable: day.orderSetting ? day.orderSetting.reservationsAvailable : 0,
  });
  dialogVisible.value = true;
};

// 提交预约设置
const submitOrderSetting = async () => {
  try {
    // 实际项目中发送请求
    // 示例API: POST /ordersetting/set
    // axios.post('/ordersetting/set', orderSettingForm).then(() => {
    ElMessage.success('预约设置成功！');
    dialogVisible.value = false;
    fetchOrderSetting(); // 重新加载数据以更新日历显示
    // }).catch(error => {
    //   ElMessage.error('预约设置失败！');
    //   console.error(error);
    // });
  } catch (error) {
    ElMessage.error('操作异常');
    console.error(error);
  }
};

// 弹窗关闭时清空表单校验状态
const handleDialogClose = () => {
  // if (orderSettingFormRef.value) {
  //   orderSettingFormRef.value.resetFields();
  // }
};

// 组件挂载时加载数据
onMounted(() => {
  goCurrentMonth(); // 默认显示当前月份数据
});
</script>

<style scoped>
/* 容器基本样式，模仿 app-container */
.app-container {
  padding: 0; /* 外部容器不设 padding，让内部 section 控制 */
  box-sizing: border-box;
}

/* 顶部区域样式 */
.top-section-container {
  background-color: #f9f9f9; /* 浅灰色背景 */
  padding: 1.25rem 1.25rem 0.625rem; /* 内边距 */
  border-bottom: 3px solid #409EFF; /* 蓝色底部边框 */
  margin-bottom: 1.25rem; /* 与下方内容区域的间距 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 底部阴影 */
}

/* 底部内容区域样式 */
.bottom-section-container {
  background-color: #ffffff; /* 白色背景 */
  padding: 1.25rem; /* 内边距 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.05); /* 阴影 */
  border-radius: 0.25rem; /* 圆角 */
  margin: 0 1.25rem 1.25rem 1.25rem; /* 左右和底部留白 */
}

/* 现有样式调整 */
.content-header {
  padding-bottom: 0.625rem; /* 保持面包屑和标题的底部间距 */
}

/* 统一 Element Plus 输入框内部样式，对应 orderset.css 中的 .ordersetting .el-input__inner */
/* 注意：这里 .ordersetting 作为组件外部类名可能无效，改为全局或更具体的选择器 */
:deep(.el-input__inner),
:deep(.el-input-number__increase),
:deep(.el-input-number__decrease) {
  height: 36px;
  line-height: 36px;
}

.calendar-section {
  /* 这个块现在已经是 bottom-section-container 的内容，不再需要额外的背景或边框 */
  /* background-color: #fff; */
  /* border: 1px solid #ebeef5; */
  border-radius: 4px;
  overflow: hidden;
}

/* 日历头部，去除之前为模拟分割线而添加的样式 */
.calendar-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 0; /* 调整内边距 */
  background-color: #f5f7fa; /* 浅灰色背景 */
  border-bottom: none; /* 移除蓝色分割线，由 top-section-container 提供 */
  padding-bottom: 10px; /* 恢复正常 padding */
}

.current-month-display.year-month { /* 对应 orderset.css 中的 .year-month */
  margin: 0 20px;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}

.current-month-display.year-month:hover { /* 对应 orderset.css 中的 .year-month:hover */
  background: rgba(150, 2, 12, 0.1);
}

.gotoday-button { /* 对应 orderset.css 中的 .gotoday */
  border: 1px solid #d5d9df;
}

/* 日历网格 */
.week-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  background-color: #f5f7fa;
  padding: 10px 0;
  font-weight: bold;
  border-bottom: 1px solid #ebeef5;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.day-item {
  min-height: 100px;
  border: 1px solid #ebeef5;
  border-top: none;
  border-left: none;
  padding: 10px;
  cursor: pointer;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  font-size: 14px;
  color: #606266;
  position: relative;
}

.day-item:nth-child(7n) {
  border-right: none;
}

.day-item:hover {
  background-color: #f2f6fc;
}

.day-item.is-current-month {
  background-color: #fff;
}

.day-item:not(.is-current-month) {
  color: #c0c4cc;
  background-color: #fcfcfc;
  cursor: default;
}

.day-item .day-number {
  position: absolute;
  top: 5px;
  right: 10px;
  font-size: 16px;
  font-weight: bold;
}

.order-info {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: calc(100% - 30px);
  margin-top: 20px;
  line-height: 1.2;
}

.order-info p {
  margin: 2px 0;
}

.day-item.is-fully-booked {
  background: #ff8a8a;
  color: #fff;
}

.day-item.is-fully-booked .day-number,
.day-item.is-fully-booked .order-info p,
.day-item.is-fully-booked .order-info span {
  color: #fff !important;
}

.order-info .available {
  color: #67c23a;
}

.order-info .reserved {
  color: #e6a23c;
}

.no-order-info p {
  color: #909399;
  text-align: center;
  width: 100%;
  margin-top: 30px;
}

.dialog-footer {
  text-align: right;
  margin-top: 1.25rem;
}
</style>